package com.googlecode.bip.util;

import java.io.Serializable;
import java.util.EnumSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import com.googlecode.bip.entity.Role;

/**
 * Helper to identify roles
 *
 * @author Claude CHOISNET
 */
public class RolesIdentifier implements Serializable
{
    private static final long serialVersionUID = 1L;
    private Set<Role> roles;

    /**
     * All existing {@link Roles} : {@value}
     */
    public static final Set<Role> ROLES = EnumSet.allOf( Role.class );

    public RolesIdentifier( final Set<Role> roles )
    {
        this.roles = roles;
    }

    public boolean isUser()
    {
        return this.roles.contains( Role.BIP_USER );
    }

    public static boolean isUser(
            final HttpServletRequest request
            )
    {
        return isUserInRole( request, Role.BIP_USER );
    }

    public boolean isReferent()
    {
        return this.roles.contains( Role.BIP_REF );
    }

    public static boolean isReferent(
            final HttpServletRequest request
            )
    {
        return isUserInRole( request, Role.BIP_REF );
    }

    public boolean isAuthor()
    {
        return this.roles.contains( Role.BIP_AUTHOR );
    }

    public static boolean isAuthor(
        final HttpServletRequest request
        )
    {
        return isUserInRole( request, Role.BIP_AUTHOR );
    }

    public boolean isAdministrator()
    {
        return this.roles.contains( Role.BIP_ADMIN );
    }

    public static boolean isAdministrator(
            final HttpServletRequest request
            )
    {
        return isUserInRole( request, Role.BIP_ADMIN );
    }

    /**
     * Returns {@link Set} of all defined {@link Roles}
     * @return {@link Set} of all defined {@link Roles}
     */
    public static Set<Role> getRoles()
    {
        return ROLES;
    }

    /**
     *
     * @param request
     * @param role
     * @return
     */
    public static boolean isUserInRole(
            final HttpServletRequest request,
            final Role               role
            )
    {
        return request.isUserInRole( role.name() );
    }

    /**
    * Returns a {@link Role} object according to rolename
    * @param rolename rolename to create
    * @return a {@link Role} object according to rolename
    * @throws IllegalArgumentException if rolename is unknown.
    */
   public static Role createRoleForName( final String rolename )
   {
       for( Role role : ROLES ) {
           if( role.name().equals( rolename ) ) {
               return role;
           }
       }
       throw new IllegalArgumentException( "Unknow rolename : " + rolename );
   }

}
